import config from 'utils/config.js'

App({
  globalData: {
    statusHeight: 0, //状态栏高度
    navHeight: 0 //标题栏高度
  },
  onLaunch() {
    if (!this.checkUserLogin()) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    this.setNavSize();
  },
  setNavSize() {
    var sysinfo = wx.getSystemInfoSync(),
      statusHeight = sysinfo.statusBarHeight,
      isiOS = sysinfo.system.indexOf('iOS') > -1,
      navHeight;
    if (!isiOS) {
      navHeight = 48;
    } else {
      navHeight = 44;
    }
    this.globalData = {
      statusHeight,
      navHeight
    }
  },
  createHeader(url) {
    const notNeedToken = ['/user/login'];
    let header = {
      'content-type': 'application/json'
    }
    if (notNeedToken.indexOf(url) === -1) {
      header.token = wx.getStorageSync('token');
    }
    return header;
  },
  fetchRequest(opt) {
    const header = this.createHeader(opt.url)
    wx.request({
      url: config.API_URL + opt.url,
      data: opt.data,
      header,
      method: opt.method || 'POST',
      dataType: 'json',
      success: (res) => {
        if (res && res.statusCode && res.statusCode === 200) {
          const response = res.data;
          if (response && response.code && response.code === 200) {
            opt.success && opt.success(response.result);
          } else {
            if (response.code === 1001003) {
              wx.navigateTo({
                url: '../login/login',
              })
            }
            opt.fail && opt.fail(response.msg);
          }
        } else {
          opt.fail && opt.fail(res);
        }
      },
      fail: (res) => {
        opt.fail && opt.fail(res);
      },
      complete: (res) => {
        opt.complete && opt.complete(res);
      }
    });
  },
  checkUserLogin() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    return !!(token && userInfo)
  }
})